/**
 * 表单输入校验
 */
(function ($) {
    function getValue(obj) {
        var type = obj.attr("type"),
            val = obj.val();
        if (type === "radio" || type === "checkbox") {
            return $("input[name='" + obj.attr("name") + "']:checked").val();
        }

        if (typeof val === "string") {
            return val.replace(/\r/g, "");
        }
        return val;
    }

    var rules = {
        required: function (obj) {
            var value = getValue(obj) || '';
            return value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') === '' ? false : true;
        },
        /**
         *正整数校验
         * @param obj
         * @returns {boolean}
         * @private
         */
        digit: function (obj) {
            return /^\d+$/.test(getValue(obj));
        },
        /**
         *number数据类型的校验
         * @param obj
         * @returns {boolean}
         * @private
         */
        number: function (obj) {
            return /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(getValue(obj));
        },
        /**
         * charNum 字符和数字校验
         * @param obj
         * @returns {boolean}
         * @private
         */
        charNum: function(obj){
        	return /^[A-Za-z0-9_]+$/.test(getValue(obj));
        },
        /**
         *email邮箱类型的校验
         * @param obj
         * @returns {boolean}
         * @private
         */
        email: function (obj) {
        	if(getValue(obj).length == 0){
        		return true;
        	}else{
        		return /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(getValue(obj));
        	}
        },
        /**
         * 日期格式校验yyyy-MM-dd、yyyy/MM/dd、yyyy/MM/dd HH、yyyy/MM/dd HH:mm等
         * @param obj
         * @returns {boolean}
         * @private
         */
        date: function (obj) {
            var value = getValue(obj);
            return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value) ||
                /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2} (\d{1,2})(:{0,1})(\d{0,2})(:{0,1})(\d{0,2})$/.test(value);
        },
        /**
         * 时间格式校验HH:mm:ss
         * @param obj
         * @returns {boolean}
         * @private
         */
        _timeCheck: function (obj) {
            var value = getValue(obj);
            return /^\d{1,2}:\d{1,2}:\d{1,2}$/.test(value);
        },
        /**
         * 起始日期比较，开始时间不能大于结束时间
         * @param obj
         * @param option
         * @returns {boolean}
         * @private
         */
        dateCompare: function (obj, option) {
            var $beginDate = $('#' + option.dateCompare);
            if (this.required($beginDate) && this.date($beginDate)) {

                if (this.required(obj)) {
                    if (this.date(obj)) {
                        var beginDate, endDate;

                        beginDate = new Date($beginDate.val().replace(/-/g, "/"));
                        endDate = new Date(obj.val().replace(/-/g, "/"));
                        return beginDate <= endDate;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }

            } else if (this.required(obj)) {
                return this.date(obj);
            }
            return true;
        },
        /**
         * 起始时间比较，开始时间不能大于结束时间【仅仅用于时分秒的比较】
         * @param obj
         * @param option
         * @returns {boolean}
         * @private
         */
        timeCompare: function (obj, option) {
            var $beginDate = $('#' + option.timeCompare);
            if (this.required($beginDate) && this._timeCheck($beginDate)) {

                if (this.required(obj)) {
                    if (this._timeCheck(obj)) {
                        var beginDate, endDate;
                        beginDate = new Date('2010/01/01 ' + $beginDate.val());
                        endDate = new Date('2010/01/01 ' + obj.val());
                        return beginDate <= endDate;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }

            } else if (this.required(obj)) {
                return this._timeCheck(obj);
            }
            return true;
        },
        /**
         * 两数字相比较
         * @param obj
         * @param option
         * @returns {boolean}
         * @private
         */
        numCompare: function (obj, option) {
            var $begin = $('#' + option.numCompare);
            var begin, end;
            begin = $begin.val();
            end = obj.val();
            if (parseInt(end) >= parseInt(begin)) {
                return true;
            } else {
                return false;
            }
        },
        /**
         * 输入框字符最短长度校验
         * @param obj
         * @param minLength
         * @returns {boolean}
         * @private
         */
        minLength: function (obj, op) {
            return getValue(obj).length >= op.minLength;
        },
        
        /**
         * 输入框字符最大长度校验
         * @param obj
         * @param maxLength
         * @returns {boolean}
         * @private
         */
        maxLength: function (obj, op) {
        	//先将汉字替换成两个英文字符，之后再取长度比较
            return getValue(obj).replace(/[^\x00-\xff]/g,"aa").length <= op.maxLength;
        },
        
        /**
         * 校验输入框如有有输入字符串就必须输入多少位
         * @param obj
         * @param length
         * @returns {boolean}
         * @private
         */
        length: function (obj, op) {
            var inputLength = getValue(obj).length;
            return !inputLength || inputLength == op.length;
        },
        /**
         * 浮点数校验
         * @param obj
         * @param integerLength 整数的最长长度
         * @param decimalLength 小数点后的最长长度
         * @private
         */
        decimal: function (obj, op) {
            var regexp = new RegExp('^\\d{1,' + op.decimal[0] + '}(\\.[0-9]{1,' + op.decimal[1] + '}){0,1}$'),
                value = getValue(obj);
            if (value) {
                return regexp.test(value);
            } else {
                return true;
            }
        }
    };
    $.validator = function ($obj, options) {
        var _t = $($obj);
        var validResult = true;
        _t.find(':text,:radio,:checkbox,textarea,select,:file,:password').filter('[data-validator]').each(function () {

            var _val = true;
            var config = $.strToJson($(this).attr('data-validator'));
            var success = true;//是否成功校验通过，主要用于不对样式进行重复设置，为false就不对样式进行设置了
            for (var prop in rules) {
                if (config[prop] !== undefined) {
                    _val = rules[prop]($(this), config);

                    if (success) {
                        if (this.tagName === 'SELECT' && this.className && this.className.indexOf('select2-offscreen') > -1) {
                            if (!_val) {
                                $(this).prev()[0].style.border = '1px solid red';
                            } else {
                                $(this).prev()[0].style.border = '';
                            }
                        } else {
                            if (!_val) {
                                this.style.border = '1px solid red';
                            } else {
                                this.style.border = '';
                            }
                        }
                        if (_val === false) {
                            success = false;
                        }
                        validResult = validResult && _val;
                    }
                }
            }
        });
        return validResult;
    }
})(jQuery);